package com.bpf.base.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


/**
 * Handles requests for the application file upload requests
 */
@Controller
@RequestMapping(value="/file")
public class FileUploadController extends BaseController
{

	private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);

	/**
	 * Upload single file using Spring Controller
	 */
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public @ResponseBody
	String uploadFileHandler(final HttpServletRequest request, @RequestParam("name") final String name,
			@RequestParam("file") final MultipartFile file, @RequestParam("fileId") final String fileId)
	{

		if (!file.isEmpty())
		{
			try
			{
				final byte[] bytes = file.getBytes();

				// Creating the directory to store file
				final String rootPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");//System.getProperty("catalina.home");
				final File dir = new File(rootPath + File.separator + fileId);
				if (!dir.exists())
				{
					dir.mkdirs();
				}

				// Create the file on server
				File serverFile = new File(dir.getAbsolutePath() + File.separator + file.getOriginalFilename());
				if (fileId.equals("0"))
				{
					serverFile = new File(dir.getAbsolutePath() + File.separator + name);
				}
				final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
				stream.write(bytes);
				stream.close();

				logger.info("Server File Location=" + serverFile.getAbsolutePath());

				return serverFile.getAbsolutePath();
			}
			catch (final Exception e)
			{
				return "You failed to upload " + name + " => " + e.getMessage();
			}
		}
		else
		{
			return "You failed to upload " + name + " because the file was empty.";
		}
	}

	/**
	 * Upload multiple file using Spring Controller
	 */
	@RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST)
	public @ResponseBody
	String uploadMultipleFileHandler(@RequestParam("name") final String[] names, @RequestParam("file") final MultipartFile[] files)
	{

		if (files.length != names.length)
		{
			return "Mandatory information missing";
		}

		String message = "";
		for (int i = 0; i < files.length; i++)
		{
			final MultipartFile file = files[i];
			final String name = names[i];
			try
			{
				final byte[] bytes = file.getBytes();

				// Creating the directory to store file
				/*
				 * String rootPath = System.getProperty("catalina.home"); File dir = new File(rootPath + File.separator +
				 * "tmpFiles"); if (!dir.exists()) dir.mkdirs();
				 */
				final File dir = new File("D:\\Joe\\test\\");
				if (!dir.exists())
				{
					dir.mkdirs();
				}

				// Create the file on server
				final File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
				final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
				stream.write(bytes);
				stream.close();

				logger.info("Server File Location=" + serverFile.getAbsolutePath());

				message = message + "You successfully uploaded file=" + name + "<br />";
			}
			catch (final Exception e)
			{
				return "You failed to upload " + name + " => " + e.getMessage();
			}
		}
		return message;
	}
}
